package io.coderyeah.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.coderyeah.basic.Result;
import io.coderyeah.system.domain.Menu;
import io.coderyeah.system.dto.MenuDTO;
import io.coderyeah.system.mapper.MenuMapper;
import io.coderyeah.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Menu)表服务实现类
 *
 * @author makejava
 * @since 2022-09-20 09:09:55
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper mapper;

    @Override
    public Result getAllMenus(MenuDTO menuDTO) {
        // 查询所有菜单
        final List<Menu> allMenus = mapper.getAllMenus(menuDTO);
        // 查询数量
        Long count = mapper.getCounts(menuDTO);
        return Result.success(allMenus, count);
    }

    @Override
    @Transactional
    public Result editType(MenuDTO menuDTO) {
        final Menu menu = new Menu();
        menu.setId(menuDTO.getId());
        menu.setState(menuDTO.getState());
        try {
            mapper.updateById(menu);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.success(null);
    }

    @Override
    public Result getMenuTree() {
        // 返回菜单树的集合
        ArrayList<Menu> list = new ArrayList<>();
        // 查询所有菜单信息
        List<Menu> menus = mapper.selectList(new LambdaQueryWrapper<>());
        // 循环遍历menus判断是否是父级菜单
        for (Menu menu : menus) {
            if (null != menu.getParentId()) {//该菜单存在父级菜单，自己是子级菜单
                // 将菜单集合转换为map提高执行效率
                Map<Long, Menu> map = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e));
                Menu parent = map.get(menu.getParentId());
                parent.getChildren().add(menu);
            } else {
                // 将父级菜单添加到集合
                list.add(menu);
            }
        }
        return Result.success(list);
    }
}

